package com.yanqu.road.server.webservice;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import com.yanqu.road.utils.net.ServerNetConfigHelper;
import com.yanqu.road.utils.net.ServerNetConfig;
import com.yanqu.road.utils.ServerType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.xml.ws.Endpoint;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class GameWebServiceHelper {

	private static Logger logger = LogManager.getLogger(GameWebServiceHelper.class.getName());

	private HttpServer httpServer;
	private Endpoint endpoint;
	private static GameWebServiceHelper gameWebServiceHelperInstance;


	private GameWebServiceHelper() {
	}

	public synchronized static GameWebServiceHelper getInstance() {
		if (null == gameWebServiceHelperInstance) {
			gameWebServiceHelperInstance = new GameWebServiceHelper();
		}
		return gameWebServiceHelperInstance;
	}

	public boolean startGameWebService() {
		ServerNetConfig netConfig = ServerNetConfigHelper.getServerNetConfig(ServerType.SERVER_WEB, 0);

		try {
			httpServer = HttpServer.create(new InetSocketAddress(netConfig.getPort()), 0);
			ExecutorService threads = Executors.newFixedThreadPool(20);
			httpServer.setExecutor(threads);
			httpServer.start();

			endpoint = Endpoint.create(new GameWebService());
			HttpContext castleContext = httpServer.createContext("/gamews");
			endpoint.publish(castleContext);

			return true;
		} catch (IOException e) {
			logger.error("webservice初始化失败", e);
		}

		return false;
	}

	public void stopGameWebService() {
		try {
			if (endpoint != null) {
				endpoint.stop();
			}
			if (httpServer != null) {
				httpServer.stop(0);
			}
		} catch (Exception e) {
			logger.error("关闭webservice失败:", e);
		}
	}
}
